#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <numeric>
using namespace std;

class Solution {
        vector<int> father;
        int find(int x)
        {       
                return father[x] == x ? x : father[x] = find(father[x]);
        }

        int merge(int x, int y)
        {
                int fx = find(x);
                int fy = find(y);
                if(fx != fy){
                        father[fx] = fy;
                        return 1;
                }
                return 0;
        }

        int is_same_set(int x, int y)
        {
                return find(x) == find(y);
        }
    public:
	vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>> &edgeList, vector<vector<int>> &queries)
	{
                for(int i = 0; i < queries.size(); i++){
                        queries[i].push_back(i);
                }
                auto cmp = [](auto &a, auto &b) { return a[2] < b[2]; };
                sort(queries.begin(), queries.end(), cmp);
                sort(edgeList.begin(), edgeList.end(), cmp);

                vector<bool> ans(queries.size(), false);
                int m = edgeList.size();
                father.resize(n);

                iota(father.begin(), father.end(), 0);
                for(int i = 0, j = 0; i < queries.size(); i++){
                        for(; j < m && edgeList[j][2] < queries[i][2]; j++){
                                merge(edgeList[j][0], edgeList[j][1]);
                        }
                        ans[queries[i][3]] = is_same_set(queries[i][0], queries[i][1]);
                }

                return ans;
        }
};

int main()
{
        int n = 3;
        vector<vector<int>> edgeList = {{0,1,2},{1,2,4},{2,0,8},{1,0,16}};
        vector<vector<int>> queries = {{0,1,2},{0,2,5}};
        vector<bool> ans = Solution().distanceLimitedPathsExist(n, edgeList, queries);
        for(auto v : ans){
                cout<<v<<" ";
        }
        cout<<endl;
        return 0;
}